import os
import sys
from google.appengine.ext import db
from google.appengine.api import users
from google.appengine.ext import webapp
from google.appengine.ext.webapp import template, util
from django.utils.feedgenerator import Rss201rev2Feed, Atom1Feed
import datetime


import json
from mode import BlogL1,BlogL2,Config
import MCache
      
class loginBlog(webapp.RequestHandler):
    def get(self):
        self.redirect(users.create_login_url('/gtBlog/admin/admin.html'),True)
        
class gtBlog(webapp.RequestHandler):
    def get(self,*args):
        umd = self.request.GET.multi;
        
        spid = umd['aid']
        arti = BlogL1.get_by_id(int(spid))
        arti.counter_visit = arti.counter_visit + 1
        db.put(arti)
        
        ####################
        sql = "SELECT * FROM BlogL2 ORDER BY date_time DESC"        
        query = db.GqlQuery(sql)
        commentList = []
        for cc in query:
            cl=[]
            n=cc.pid.key().id()
            sn = str(n)
            if  sn == spid:
#                cl.append(cc.content)
#                cl.append(str(cc.date_time))
                commentList.append(cc)
        #########
        lSidebar = MCache.getCacheConfig()["sidebar"]
        template_file = os.path.join(os.path.dirname(__file__), 'templates','artical.html')
        vars = { 
             'aid':             spid,
             'title':           arti.title,
             'tags':            arti.tags,
             'content':         arti.content,
             'date_time':       arti.date_time,
             'counter_visit':   arti.counter_visit,
             'commentList':     commentList,
             'configQuery':     lSidebar[1:],
             'commentCount':    len(commentList),
             'blogTitle':       lSidebar[0]
             }        
        rendered = webapp.template.render(template_file, vars, debug=True)
        self.response.out.write(rendered)
    def post(self):
        spid = self.request.GET.multi["aid"]
        arti = BlogL1.get_by_id(int(spid))
        arti.counter_comment = arti.counter_comment+1;
        db.put(arti)
        
        comment = BlogL2(pid=arti,content=self.request.get("content"),username=self.request.get("username") )
        comment.put()
        ####################
        sql = "SELECT * FROM BlogL2 ORDER BY date_time DESC"        
        query = db.GqlQuery(sql)
        commentList = []
        for cc in query:
            cl=[]
            n=cc.pid.key().id()
            sn = str(n)
            if  sn == spid:
#                cl.append(cc.content)
#                cl.append(str(cc.date_time))
                commentList.append(cc)
        lSidebar = MCache.getCacheConfig()["sidebar"]
        template_file = os.path.join(os.path.dirname(__file__), 'templates','artical.html')
        vars = { 
             'aid':             spid,
             'title':           arti.title,
             'tags':            arti.tags,
             'content':         arti.content,
             'date_time':       arti.date_time,
             'counter_visit':   arti.counter_visit,
             'commentList':     commentList,
             'configQuery':     lSidebar[1:],
             'commentCount':    len(commentList),
             'blogTitle':       lSidebar[0]
             }        
        rendered = webapp.template.render(template_file, vars, debug=True)
        self.response.out.write(rendered)
class JSONHandler_Blog(webapp.RequestHandler,json.JSONRPC):
    def post(self):
        response, code = self.handleRequest(self.request.body, self.HTTP_POST)
        self.response.headers['Content-Type'] = 'application/json'
        self.response.set_status(code)
        self.response.out.write(response)


    def json_blogShow(self,num):
        if num == 0:
            return MCache.getCacheBlogL1Page0()
        s_offset=str(num*10)
        sql = "SELECT * FROM BlogL1 ORDER BY date_time DESC LIMIT "+ s_offset+ ", 10"
        blogL1_set = db.GqlQuery(sql)
        strlist = []
        for artical in blogL1_set:
            strlist1=[]
            strlist1.append(artical.key().id())
            strlist1.append(artical.title)
            strlist1.append(artical.tags)
            strlist1.append(artical.intro)
            strlist1.append(artical.date_time.strftime('%Y-%m-%d %H:%M:%S') )
            strlist1.append(str(artical.counter_visit))
            strlist1.append(str(artical.counter_comment))
            strlist.append(strlist1)
        return strlist
    def json_getPages(self):
        return MCache.getCacheConfig()
    
class JSONHandler_Admin(webapp.RequestHandler,json.JSONRPC):
    def post(self):

        response, code = self.handleRequest(self.request.body, self.HTTP_POST)
        self.response.headers['Content-Type'] = 'application/json'
        self.response.set_status(code)
        self.response.out.write(response)

    def json_adminGetTitles(self,num):
        user = users.get_current_user()
        if user == None:
            return ''
        if users.is_current_user_admin()== False:
            return ''

        s_offset=str(num*20)
        sql = "SELECT * FROM BlogL1 ORDER BY date_time DESC LIMIT "+ s_offset+ ", 20"
        blogL1_set = db.GqlQuery(sql)
        dRet = {}
        dRet['counter_arti']=BlogL1.all().count()
        
        strlist = []
        for artical in blogL1_set:
            strlist1=[]
            strlist1.append(artical.key().id())
            strlist1.append(artical.title)
            strlist1.append(str(artical.date_time))
            strlist.append(strlist1)
        dRet['titles']=strlist
        return dRet
        
    def json_adminNewPost(self,aid,stitle,stags,sIntro,scontent):
        user = users.get_current_user()
        if user == None:
            return ''
        if users.is_current_user_admin()== False:
            return ''
        
        ustitle= unicode(stitle,"utf-8")
        ustags=unicode(stags,"utf-8")
        usIntro = unicode(sIntro,"utf-8")
        uscontent= unicode(scontent,"utf-8")

        if aid == '':
             artical = BlogL1(title=ustitle,intro=usIntro,tags=ustags,content=uscontent,visiable_lv=1,counter_visit=0,counter_comment=0)
             artical.put()
        else:
            arti = BlogL1.get_by_id(int(aid))
            if arti:
                arti.title = ustitle
                arti.tags = ustags
                arti.intro = usIntro
                arti.content = uscontent
                db.put(arti)
        
        MCache.RefreshBlogL1Page0()
        MCache.RefreshCacheConfig()
        return "haha";
    
    def json_adminGetArtical(self,aid):
        user = users.get_current_user()
        if user == None:
            return ''
        if users.is_current_user_admin()== False:
            return ''

        artical = BlogL1.get_by_id(aid)
        strlist1=[]
        strlist1.append(artical.title)
        strlist1.append(artical.tags)
        strlist1.append(artical.intro)
        strlist1.append(artical.content)
        return strlist1
    def json_adminPostDel(self,aid):
        user = users.get_current_user()
        if user == None:
            return ''
        if users.is_current_user_admin()== False:
            return ''

        sql = "SELECT * FROM BlogL2 ORDER BY date_time DESC"        
        query = db.GqlQuery(sql)
        commentList = []
        for cc in query:
            cl=[]
            n=cc.pid.key().id()
            if  n == aid:
                db.delete(cc)
        artical = BlogL1.get_by_id(aid)
        if artical:
            artical.delete()
        ##
        MCache.RefreshBlogL1Page0()
        MCache.RefreshCacheConfig()
        
    def json_adminSidebars(self,dSidebar):
        user = users.get_current_user()
        if user == None:
            return ''
        if users.is_current_user_admin()== False:
            return ''

        atype = dSidebar['type']
        dPost={}
        if atype == 'get':
            dPost['type']='get'
            query = Config.all()
            lContent=[]
            for item in query:
                lContent.append(item.content)
            dPost['content']=lContent
        elif atype == 'update':
            query = Config.all()
            db.delete(query)
            lContent = dSidebar['content']
            for il in lContent:
                item = Config(type=1,content=unicode(il,"UTF-8") )
                item.put()
            dPost['type']='post'
            MCache.RefreshCacheConfig()
        elif atype == 'new':
            dPost['type']='new'
            dPost['content']=[]
            lContent = dSidebar['content']
            for il in lContent:
                item = Config(type=1,content=unicode(il,"UTF-8"))
                item.put()
            MCache.RefreshCacheConfig()            
        return  dPost
    def json_adminGetLoginUrl(self,url):
        #user = users.get_current_user()
        
        newurl=[]
        newurl.append(users.create_login_url(url))
        newurl.append(users.create_logout_url('/login'))
        return newurl
    
class Feed(webapp.RequestHandler):
	def get(self):
		feed_type = self.request.get('type')
		if feed_type.lower() == 'atom' or feed_type.lower() == 'atom1':
			feed_type = 'atom1'
		else:
			feed_type = 'rss2'

		tag = self.request.get('tag')

		feed_title = 'godtime'

		sql = "SELECT * FROM BlogL1 ORDER BY date_time DESC"
		posts = db.GqlQuery(sql)

		if feed_type == 'rss2':
			feed = Rss201rev2Feed(
					title = feed_title,
					link = 'http://www.google.cn',
					description= u'test',
					subtitle = 'aa'
					)
		elif feed_type == 'atom1':
			feed = Atom1Feed(
					title = feed_title,
					link = 'http://www.google.cn',
					description= u'test',
					subtitle = 'aa'
					)

		for post in posts:
			post_url = 'http://www.g.cn'

			if feed_type == 'rss2':
				feed.add_item(
						title = post.title,
						author_email = 'godtim@g.cn',
						link = post_url,
						description = post.content,
						pubdate = str(post.date_time),
						unique_id = post_url,
						categories = post.tags
						)
			elif feed_type == 'atom1':
				feed.add_item(
						title = post.title,
						author_name = 'godtime',
						link = 'hah',
						description = post.content,
						pubdate = post.date,
						unique_id = post_url,
						categories = post.tags
						)

		self.response.headers['Content-Type'] = 'application/rss+xml; charset=utf-8'
		from StringIO import StringIO
		buffer = StringIO()
		feed.write(buffer, 'utf-8')
		feed_xml = buffer.getvalue()
		buffer.close()
		self.write(feed_xml)
		
def main():
    app = webapp.WSGIApplication([
        ('/services/', JSONHandler_Blog),
        ('/admin',JSONHandler_Admin),
        ('/gtBlog',gtBlog),
        ('/login',loginBlog),
        ('/feed',Feed)
        ], debug=True)
    util.run_wsgi_app(app)

if __name__ == '__main__':
    main()
